import wxvalidate from 'wechat-validate'
Page({
  behaviors: [wxvalidate],
  data: {
    dateLayerVisible: false,
    houseLayerVisible: false,
    houseList: [],
    name: '',
    gender: 1,
    visitDate: '',
    // 最小时间 当前时间
    currentDate: Date.now(),
    // 最大时间 , 最多往后延长三天
    maxDate: Date.now() + 1000 * 3600 * 24 * 3,
    mobile: '',
    houseInfo: '',
    houseId: '',
  },
  // 校验规则
  rules: {
    name: [
      { required: true, message: '访客姓名为空' },
      { pattern: /^(?:[\u4e00-\u9fa5·]{2,16})$/, message: '请检查姓名' },
    ],
    mobile: [
      { required: true, message: '访客手机号不能为空' },
      { pattern: /^1[3-9]\d{9}$/, message: '手机号格式错误' },
    ],
    visitDate: [{ required: true, message: '请选择访问日期' }],
    houseInfo: [{ required: true, message: '请选择房屋' }],
  },
  onLoad() {
    this.getHouseList()
  },

  // 获取房屋列表
  async getHouseList() {
    const { code, data: houseList } = await wx.http.get('/house')
    if (code !== 10000) return wx.utils.toast()
    this.setData({
      houseList,
    })
  },

  selectHouseInfo(e) {
    this.setData({
      houseInfo: e.detail.name,
      houseId: e.detail.id,
    })
  },

  selectDateInfo(e) {
    // console.log(e)
    this.setData({
      visitDate: wx.utils.dataFormat(e.detail),
      dateLayerVisible: false,
    })
  },
  openHouseLayer() {
    this.setData({ houseLayerVisible: true })
  },
  closeHouseLayer() {
    this.setData({ houseLayerVisible: false })
  },
  openDateLayer() {
    this.setData({ dateLayerVisible: true })
  },
  closeDateLayer() {
    this.setData({ dateLayerVisible: false })
  },
  async goPassport() {
    // 对表单进行校验
    if (!this.validate()) return
    // 调新增访客接口 拿到返回的访客ID 跳转到访客详情页面
    const { houseId, name, mobile, gender, visitDate } = this.data
    const {
      code,
      data: { id },
    } = await wx.http.post('/visitor', { houseId, name, mobile, gender, visitDate })
    if (code !== 10000) return wx.utils.toast()
    // console.log(id)
    // reLaunch 跳转非tabBar的新页面 并且清空页面栈中的页面实例
    wx.reLaunch({
      url: '/visitor_pkg/pages/passport/index?id=' + id,
    })
  },
})
